<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input  v-model="query.name" placeholder="请输入角色名称" class="filter-item" style="width: 500px;margin-right: 5px;" ></el-input>
      <el-button @click="getRecords" type="primary" class="filter-item">查询</el-button>
      <el-button @click="openAddDialog" type="primary" class="filter-item">添加</el-button>
      <el-button @click="reload" type="danger" class="filter-item">刷新</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
    <el-table-column
      type="selection"
      width="55" />
    <el-table-column prop="id" label="ID" width="80" />
    <el-table-column prop="name" label="角色名称" width="120" />
    <el-table-column prop="permission_names" label="权限" width="400" />
    <el-table-column prop="beizhu" label="备注" width="150" />
    <el-table-column prop="created_at" label="创建时间" width="160" />
    <el-table-column fixed="right" label="操作" width="200">
      <template slot-scope="scope">
				<el-button
				size="mini"
				@click="handleEdit(scope.$index, scope.row)">编辑</el-button>
				<el-button
				size="mini"
				type="danger"
				@click="handleDelete(scope.$index, scope.row)">删除</el-button>
			</template>
    </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[5,10, 20, 100, 200]"
      :page-size="pagination.pageSize"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total">
    </el-pagination>

    <el-dialog :title="isAdd?'添加角色':'编辑角色'" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.beizhu"></el-input>
        </el-form-item>
        <el-form-item label="权限">
          <el-tree
            ref="tree"
            :data="permission"
            show-checkbox
            node-key="id"
            :default-checked-keys="form.selectPermissionIds"
            :default-expand-all="true"
            :props="defaultProps">
          </el-tree>
        </el-form-item>

        <el-form-item v-if="isAdd">
          <el-button type="primary" @click="onSubmit('form')">立即创建</el-button>
          <el-button>取消</el-button>
        </el-form-item>
        <el-form-item v-else>
          <el-button type="primary" @click="onSubmit('form')">修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import { myGet, myPost } from '@/utils/myRequest'

  const urlRoleLst = '/guard/rbac/role/lst'
  const urlAddRole = '/guard/rbac/role/add'
  const urlGetRole = '/guard/rbac/role/getRole'
  const urlDelRole = '/guard/rbac/role/del'
  const urlPermissionLst = '/guard/rbac/permission/lst'

export default {

  data() {
    return {
      isAdd:true,
      permission:[],
      listLoading: false,
      dialogFormVisible:false,
      list: [],
      query:{
        name:'',
      },
      pagination:{
        page:1,
        pageSize:5,
        total:0,
      },
      form:{
        name: '',
        beizhu:'',
        selectPermissionIds:[],
      },
      defaultProps: {
        children: 'children',
        label: 'title',
      },
      rules:{
        name:[
          { required: true, message: '必填', trigger: 'blur' }
        ]
      },
    }
  },

  methods: {
    reload(){
      Object.assign(this.$data.query,this.$options.data().query)
      Object.assign(this.$data.pagination,this.$options.data().pagination)
      this.getRecords()
    },
    getRecords(){
      this.listLoading = true
      const params = Object.assign(this.query,this.pagination)
      myGet(urlRoleLst,params).then(res=>{
        this.listLoading = false;
        if(res.status) {
          this.list = res.data.records
          this.pagination.total = res.data.total
        }
      })
    },

    getPermission(){
      myGet(urlPermissionLst).then(res=>{
        if(res.status) {
          this.permission = res.data.records
        }
      })
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid)=>{
        if(valid){
          this.form.permissionIds = this.$refs.tree.getCheckedKeys().join(',')
          this.dialogFormVisible = true
          myPost(urlAddRole,this.form).then(res => {
            this.dialogFormVisible = false
            if(res.status){
              this.$message.success(res.msg)
              this.reload()
            }
          })
        }
      })
    },

    async handleEdit(index,row){
      this.isAdd = false;
      this.dialogFormVisible = true
      const id = row.id
      const resRole =  await myGet(urlGetRole,{id})
      if (resRole.status) {
        const info = resRole.data.records[0]
        const {id,name,beizhu,permission_ids} = info
        Object.assign(this.form,{id,name,beizhu,permission_ids})
        info.permission_ids.split(',').forEach(item=>{
          this.form.selectPermissionIds.push(item)
        })
        this.getPermission()
      }
    },

    handleDelete(index,row){
        this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const id = row.id
          myGet(urlDelRole,{id}).then(res => {
            if(res.status){
              this.$message.success(res.msg)
              this.reload();
            }
          })
        });
      },

    openAddDialog(){
      this.dialogFormVisible = true
      Object.assign(this.data.form, this.$options.data().form)
      this.getPermission()
    },

    closeAddDialog(){
      this.dialogFormVisible= false
      Object.assign(this.data.form, this.$options.data().form)
    },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.currentPage = 1
        this.getRecords()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getRecords();
      },

  },
  mounted() {
    this.getRecords();
  },
}
</script>


